/*
 * 文件名：LookInfoController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月10日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.domain.LookInfoDomain;
import top.infopub.mgr.cap.dto.LookInfoDto;
import top.infopub.mgr.cap.jsonvo.CapLookInfoJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.LookInfoService;
import top.infopub.mgr.cap.vo.LookInfoBeginVo;
import top.infopub.mgr.cap.vo.LookInfoVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.LookInfo;
import top.infopub.model.cap.LookInfoAtt;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 融资尽调管理
 * @author wuzhiyang
 * @version 2020年1月10日
 * @see LookInfoController
 * @since
 */
@Controller
@RequestMapping("/lookInfo")
public class LookInfoController extends GenericFlowController {

    @Autowired
    private LookInfoService lookInfoService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    /**
     * 融资尽调列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<LookInfoDomain> queryDataByCondition(LookInfoBeginVo lookInfoBeginVo, ParamPage paramPage) {
        Page<LookInfoDomain> page = new Page<LookInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = lookInfoService.selectByDomainWhere(page, lookInfoBeginVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资尽调列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<LookInfoDomain> queryMyCheckDataByCondition(LookInfoVo lookInfoVo,
                                                             ParamPage paramPage) {
        Page<LookInfoDomain> page = new Page<LookInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (lookInfoVo.getEndDate() != null) {
            lookInfoVo.setEndDate(DateUtils.addDays(lookInfoVo.getEndDate(), 1));
        }
        //增加addby
        lookInfoVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = lookInfoService.selectMyCheckByDomainWhere(page, lookInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }




    private LookInfoAtt createFileAtt(AuthorizationVO vo, String lookInfoId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        LookInfoAtt fileAtt = new LookInfoAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        fileAtt.setLookInfoId(lookInfoId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "lookInfoAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资尽调附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询预立项详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 预立项Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id",id);
        LookInfo lookInfo = lookInfoService.selectBySguid(id);
        request.setAttribute("isAuditFlag", "1");
        if (lookInfo!=null){
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), lookInfo.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), lookInfo.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(lookInfo.getProcessId()) && lookInfo.getProcessId().length() > 10){
                request.setAttribute("processId", lookInfo.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(lookInfo.getProcessId(), vo);
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), lookInfo.getProcessStatus())
                    && StringUtils.equals("0", auditTabFlag)) {
                request.setAttribute("isAuditFlag", "0");
            }
            request.setAttribute("auditTabFlag", auditTabFlag);
        }
       }
        return new ModelAndView("cap/lay-FinancingDueDiligence-detail");
    }

    /**
     * 融资尽调详情
     */
    @RequestMapping("/queryLookInfo")
    @ResponseBody
    public RspVo queryLookInfoBegin(String id) {
        LookInfoDto lookInfoDto = lookInfoService.queryDetailById(id);
        return RspVo.getSuccessResponse(lookInfoDto);
    }

    /**
     * 融资尽调保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String bodyStr,Integer submitType) {
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        String s = StringEscapeUtils.unescapeJava(bodyStr);
        CapLookInfoJsonVo vo = JSON.parseObject(s, CapLookInfoJsonVo.class);
        /**
         * 附件处理
         * */
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(vo.getFileAtt()!=null){
            String[] fileAtt = vo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(userDtl,vo.getLookInfoDto().getProCode(),file);
                attachmentList.add(attachment);
            }
        }
        return lookInfoService.saveAll(vo,userDtl,attachmentList,submitType,bodyStr);
    }
    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg,String isTrack) {

        //融资立项
        capProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }
}
